package com.pan.crawler.auto2;

import com.pan.crawler.Page;
import com.pan.crawler.auto2.action.NextPage;
import com.pan.crawler.auto2.action.RegexTool;
import com.pan.crawler.auto2.action.XPathFind;
import com.pan.crawler.factory.EdgeDriverFactory;
import com.pan.entity.Chapter;
import com.pan.download5.parse.entity.auto2.Auto2InfoPage;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.time.Duration;

public class Auto2CrawlerPage implements Page {


    private String contentXPath;
    private String contentRegex;
    private NextPage nextPage;

    private EdgeDriver edgeDriver;
    private XPathFind xPathFind;
    private RegexTool regexTool;
    public Auto2CrawlerPage(Auto2InfoPage auto2InfoPage) {

        this.contentXPath = auto2InfoPage.getContent().getXpath();
        this.contentRegex = auto2InfoPage.getContent().getRegex();
        nextPage  = new NextPage(auto2InfoPage.getNext());


        regexTool = new RegexTool();
        xPathFind = new XPathFind();



        //临时措施
        this.edgeDriver = (EdgeDriver) new EdgeDriverFactory().getDriver();
//        edgeDriver = new EdgeDriver();
//        EdgeOptions edgeOptions = new EdgeOptions();
//        edgeOptions.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
    }

    @Override
    public String get(Chapter chapter) {
        String url = chapter.getUrl();
        edgeDriver.navigate().to(url);
        StringBuffer content = new StringBuffer();
        do {
            String c = xPathFind.find(edgeDriver, contentXPath);
            content.append(c);
        }while (nextPage.next(edgeDriver));
        String result = regexTool.handle(contentRegex, content.toString());
        return result;
    }

    @Override
    public void close() {
        edgeDriver.quit();
    }
}
